import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
import Cookies from 'js-cookie'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    token: Cookies.get('token') || '',
    user: JSON.parse(localStorage.getItem('user')) || null
  },
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token
      Cookies.set('token', token, { expires: 7 })
    },
    SET_USER(state, user) {
      state.user = user
      localStorage.setItem('user', JSON.stringify(user))
    },
    CLEAR_AUTH(state) {
      state.token = ''
      state.user = null
      Cookies.remove('token')
      localStorage.removeItem('user')
    }
  },
  actions: {
    // 验证token
    async validateToken({ state, commit }) {
      try {
        console.log('验证token有效性')
        if (!state.token) {
          console.log('没有token，无需验证')
          return false
        }
        
        // 使用stats API来验证token，因为它是需要认证的
        const response = await axios.get('/admin/stats')
        console.log('token验证成功，stats API返回:', response.data)
        return true
      } catch (error) {
        console.error('token验证失败，可能已过期:', error)
        // 如果token无效，清除认证状态
        commit('CLEAR_AUTH')
        return false
      }
    },
    
    // 登录
    async login({ commit }, credentials) {
      try {
        console.log('尝试登录:', { username: credentials.username })
        const response = await axios.post('/admin/login', credentials)

        // 打印完整的响应数据结构
        console.log('登录响应完整数据:', response.data)
        console.log('响应数据类型:', typeof response.data)
        console.log('响应数据字段:', Object.keys(response.data))

        // 检查数据结构并适配
        let token, user
        if (response.data.data) {
          // 如果有data字段，从data中获取
          ({ token, user } = response.data.data)
        } else if (response.data.token) {
          // 如果直接在根级别有token字段
          token = response.data.token
          user = response.data.user || response.data
        } else {
          // 如果都没有，抛出错误
          console.error('无法从响应中找到token，响应结构:', response.data)
          throw new Error('登录响应格式不正确，缺少token')
        }

        console.log('解析出的token:', token)
        console.log('解析出的user:', user)

        commit('SET_TOKEN', token)
        commit('SET_USER', user)
        return user
      } catch (error) {
        console.error('登录失败:', error)
        throw error
      }
    },
    
    // 登出
    logout({ commit }) {
      commit('CLEAR_AUTH')
    },
    
    // 获取用户列表
    async fetchUsers(_, params) {
      try {
        console.log('获取用户列表, 参数:', params)
        const response = await axios.get('/admin/users', { params })
        console.log('用户列表API返回的完整数据:', response.data)
        console.log('用户列表数据结构:', response.data.data)
        return response.data.data
      } catch (error) {
        console.error('获取用户列表失败:', error)
        throw error
      }
    },
    
    // 添加用户
    async addUser(_, userData) {
      try {
        console.log('添加用户:', userData)
        const response = await axios.post('/admin/users', userData)
        return response.data.data
      } catch (error) {
        console.error('添加用户失败:', error)
        throw error
      }
    },
    
    // 更新用户
    async updateUser(_, { id, userData }) {
      try {
        console.log('更新用户:', { id, userData })
        const response = await axios.put(`/admin/users/${id}`, userData)
        return response.data.data
      } catch (error) {
        console.error('更新用户失败:', error)
        throw error
      }
    },
    
    // 删除用户
    async deleteUser(_, id) {
      try {
        console.log('删除用户:', { id })
        await axios.delete(`/admin/users/${id}`)
        return true
      } catch (error) {
        console.error('删除用户失败:', error)
        throw error
      }
    },
    
    // 获取句子列表
    async fetchSentences(_, params) {
      try {
        console.log('获取句子列表, 参数:', params)
        const response = await axios.get('/admin/sentences', { params })
        console.log('句子列表API返回的完整数据:', response.data)
        console.log('句子列表数据结构:', response.data.data)
        return response.data.data
      } catch (error) {
        console.error('获取句子列表失败:', error)
        throw error
      }
    },
    
    // 添加句子
    async addSentence(_, sentenceData) {
      try {
        console.log('添加句子:', sentenceData)
        const response = await axios.post('/admin/sentences', sentenceData)
        return response.data.data
      } catch (error) {
        console.error('添加句子失败:', error)
        throw error
      }
    },
    
    // 更新句子
    async updateSentence(_, { id, content }) {
      try {
        console.log('更新句子:', { id, content })
        const response = await axios.put(`/admin/sentences/${id}`, { content })
        return response.data.data
      } catch (error) {
        console.error('更新句子失败:', error)
        throw error
      }
    },
    
    // 删除句子
    async deleteSentence(_, id) {
      try {
        console.log('删除句子:', { id })
        await axios.delete(`/admin/sentences/${id}`)
        return true
      } catch (error) {
        console.error('删除句子失败:', error)
        throw error
      }
    },
    
    // 获取录音列表
    async fetchRecordings(_, params) {
      try {
        console.log('获取录音列表, 参数:', params)
        const response = await axios.get('/admin/recordings', { params })
        console.log('录音列表API返回的完整数据:', response.data)
        console.log('录音列表数据结构:', response.data.data)
        return response.data.data
      } catch (error) {
        console.error('获取录音列表失败:', error)
        throw error
      }
    },
    
    // 删除录音
    async deleteRecording(_, id) {
      try {
        console.log('删除录音:', { id })
        await axios.delete(`/admin/recordings/${id}`)
        return true
      } catch (error) {
        console.error('删除录音失败:', error)
        throw error
      }
    },
    
    // 导出用户录音
    async exportUserRecordings(_, userId) {
      try {
        console.log('导出用户录音:', { userId })
        const response = await axios.get(`/admin/recordings/export/user/${userId}`, {
          responseType: 'blob'
        })
        return response.data
      } catch (error) {
        console.error('导出用户录音失败:', error)
        throw error
      }
    },
    
    // 导出句子录音
    async exportSentenceRecordings(_, sentenceId) {
      try {
        console.log('导出句子录音:', { sentenceId })
        const response = await axios.get(`/admin/recordings/export/sentence/${sentenceId}`, {
          responseType: 'blob'
        })
        return response.data
      } catch (error) {
        console.error('导出句子录音失败:', error)
        throw error
      }
    },
    
    // 导出所有录音
    async exportAllRecordings() {
      try {
        console.log('导出所有录音')
        const response = await axios.get('/admin/recordings/export/all', {
          responseType: 'blob'
        })
        return response.data
      } catch (error) {
        console.error('导出所有录音失败:', error)
        throw error
      }
    },
    
    // 获取系统统计数据
    async fetchStats() {
      try {
        console.log('获取系统统计数据')
        const response = await axios.get('/admin/stats')
        return response.data.data
      } catch (error) {
        console.error('获取系统统计数据失败:', error)
        throw error
      }
    },
    
    // 获取单个录音详情
    async fetchRecordingDetail(_, id) {
      try {
        console.log('获取录音详情:', { id })
        const response = await axios.get(`/admin/recordings/${id}`)
        console.log('录音详情返回数据状态码:', response.status)
        console.log('录音详情返回headers:', response.headers)
        
        // 详细检查返回的数据结构
        const data = response.data
        console.log('录音详情返回数据结构:', {
          hasCode: 'code' in data,
          code: data.code,
          hasData: 'data' in data,
          dataType: data.data ? typeof data.data : 'undefined',
          dataFields: data.data ? Object.keys(data.data) : []
        })
        
        if (data.data && data.data.audio_content) {
          console.log('音频内容类型:', typeof data.data.audio_content)
          console.log('音频内容长度:', data.data.audio_content.length)
          console.log('音频内容前30个字符:', data.data.audio_content.substring(0, 30))
        } else {
          console.log('返回的数据中没有音频内容')
        }
        
        return response.data.data
      } catch (error) {
        console.error('获取录音详情失败:', error)
        throw error
      }
    },
    
    // 获取最新录音
    async fetchLatestRecordings(_, limit = 5) {
      try {
        console.log('获取最新录音, 限制:', limit)
        const response = await axios.get('/admin/recordings/latest', {
          params: { limit }
        })
        return response.data.data
      } catch (error) {
        console.error('获取最新录音失败:', error)
        throw error
      }
    },
    
    // 获取用户录音数量
    async fetchUserRecordingCount(_, userId) {
      try {
        console.log('获取用户录音数量:', { userId })
        const response = await axios.get(`/admin/recordings/count/user/${userId}`)
        // 只返回录音数量，而不是整个对象
        return response.data.data.recording_count || 0
      } catch (error) {
        console.error('获取用户录音数量失败:', error)
        throw error
      }
    },
    
    // 获取句子录音数量
    async fetchSentenceRecordingCount(_, sentenceId) {
      try {
        console.log('获取句子录音数量:', { sentenceId })
        const response = await axios.get(`/admin/recordings/count/sentence/${sentenceId}`)
        // 只返回录音数量，而不是整个对象
        return response.data.data.recording_count || 0
      } catch (error) {
        console.error('获取句子录音数量失败:', error)
        throw error
      }
    },
    
    // 下载录音文件（通过ID）
    async downloadRecording(_, recordingId) {
      try {
        console.log('下载录音文件(通过ID):', recordingId)
        
        // 使用blob格式接收音频数据
        const response = await axios.get(`/admin/recordings/download/${recordingId}`, {
          responseType: 'blob'
        });
        
        // 检查响应类型
        const contentType = response.headers['content-type'];
        console.log('音频文件类型:', contentType);
        
        // 检查是否是音频文件或二进制文件
        if (contentType && (contentType.includes('audio') || contentType.includes('octet-stream'))) {
          // 创建新的blob对象，尝试多种音频格式
          let blob = response.data;
          
          // 如果是wav格式，尝试确保用正确的mime类型
          if (contentType.includes('wav') || recordingId.toString().includes('.wav')) {
            blob = new Blob([response.data], {type: 'audio/wav'});
          }
          
          // 创建URL
          const audioUrl = URL.createObjectURL(blob);
          
          return {
            blob: blob,
            url: audioUrl,
            contentType: contentType
          };
        } else {
          console.error('响应不是音频格式:', contentType);
          throw new Error('服务器返回的不是音频格式');
        }
      } catch (error) {
        console.error('下载录音文件失败:', error);
        throw error;
      }
    },
    
    // 下载音频文件（通过文件路径）
    async downloadAudioFile(_, filePath) {
      try {
        console.log('下载音频文件(通过路径):', filePath);

        // 处理文件路径
        let path = filePath;
        if (path.startsWith('/')) {
          path = path.substring(1);
        }

        // 使用fetch API直接获取音频文件
        const token = Cookies.get('token');
        const url = `${axios.defaults.baseURL}/admin/recordings/file/${encodeURIComponent(path)}`;

        console.log('音频文件URL:', url);

        const response = await fetch(url, {
          method: 'GET',
          headers: {
            'Authorization': `Bearer ${token}`
          }
        });

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        // 获取响应的blob
        const blob = await response.blob();
        const contentType = blob.type;
        console.log('音频文件类型:', contentType);

        // 创建一个本地URL
        const audioUrl = URL.createObjectURL(blob);
        return {
          blob: blob,
          url: audioUrl,
          contentType
        };
      } catch (error) {
        console.error('下载音频文件失败:', error);
        throw error;
      }
    },

    // ==================== 句子分配管理 ====================

    // 获取分配概览
    async fetchAssignmentOverview() {
      try {
        console.log('获取分配概览')
        const response = await axios.get('/admin/assignments/overview')
        console.log('分配概览API返回:', response.data)
        return response.data.data
      } catch (error) {
        console.error('获取分配概览失败:', error)
        throw error
      }
    },

    // 获取用户分配详情
    async fetchUserAssignments(_, userId) {
      try {
        console.log('获取用户分配详情:', userId)
        const response = await axios.get(`/admin/assignments/user/${userId}`)
        console.log('用户分配详情API返回:', response.data)
        return response.data.data
      } catch (error) {
        console.error('获取用户分配详情失败:', error)
        throw error
      }
    },

    // 分配句子给用户
    async assignSentences(_, { userId, sentenceIds, replaceExisting = true }) {
      try {
        console.log('分配句子给用户:', { userId, sentenceIds, replaceExisting })
        const response = await axios.post('/admin/assignments/assign', {
          user_id: userId,
          sentence_ids: sentenceIds,
          replace_existing: replaceExisting
        })
        console.log('分配句子API返回:', response.data)
        return response.data.data
      } catch (error) {
        console.error('分配句子失败:', error)
        throw error
      }
    },

    // 随机分配句子
    async assignRandomSentences(_, { userId, count, category = null }) {
      try {
        console.log('随机分配句子:', { userId, count, category })
        const response = await axios.post('/admin/assignments/assign-random', {
          user_id: userId,
          count: count,
          category: category
        })
        console.log('随机分配API返回:', response.data)
        return response.data.data
      } catch (error) {
        console.error('随机分配句子失败:', error)
        throw error
      }
    },

    // 批量分配句子
    async batchAssignSentences(_, { userIds, assignmentType, count, sentenceIds = null }) {
      try {
        console.log('批量分配句子:', { userIds, assignmentType, count, sentenceIds })
        const response = await axios.post('/admin/assignments/batch-assign', {
          user_ids: userIds,
          assignment_type: assignmentType,
          count: count,
          sentence_ids: sentenceIds
        })
        console.log('批量分配API返回:', response.data)
        return response.data.data
      } catch (error) {
        console.error('批量分配句子失败:', error)
        throw error
      }
    },

    // 清空用户分配
    async clearUserAssignments(_, userId) {
      try {
        console.log('清空用户分配:', userId)
        const response = await axios.delete(`/admin/assignments/clear/${userId}`)
        console.log('清空分配API返回:', response.data)
        return response.data.data
      } catch (error) {
        console.error('清空用户分配失败:', error)
        throw error
      }
    },

    // 获取句子使用统计
    async fetchSentenceStats() {
      try {
        console.log('获取句子使用统计')
        const response = await axios.get('/admin/assignments/sentence-stats')
        console.log('句子统计API返回:', response.data)
        return response.data.data
      } catch (error) {
        console.error('获取句子统计失败:', error)
        throw error
      }
    }
  },
  getters: {
    isAuthenticated: state => !!state.token,
    token: state => state.token,
    user: state => state.user
  }
}) 